package cn.com.thinvent.dispatch.web.controller;

import cn.com.thinvent.dispatch.entity.StudyManagement;
import cn.com.thinvent.dispatch.entity.request.StudyManagementRequest;
import cn.com.thinvent.dispatch.entity.response.PagedGridResult;
import cn.com.thinvent.dispatch.entity.response.ReturnModel;
import cn.com.thinvent.dispatch.service.biz.StudyManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/study")
public class StudyManagementController {

    @Autowired
    private StudyManagementService studyManagementService;

    @PostMapping("/add")
    public ReturnModel addStudy(@RequestBody StudyManagementRequest studyManagementRequest) {
        try {
            StudyManagement savedStudy = studyManagementService.save(studyManagementRequest);
            return new ReturnModel(200, savedStudy, "添加学习管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "添加学习管理记录失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public ReturnModel deleteStudy(@PathVariable String id) {
        try {
            studyManagementService.deleteById(id);
            return new ReturnModel(200, null, "删除学习管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "删除学习管理记录失败：" + e.getMessage());
        }
    }

    @PutMapping("/update")
    public ReturnModel updateStudy(@RequestBody StudyManagementRequest studyManagementRequest) {
        try {
            StudyManagement updatedStudy = studyManagementService.update(studyManagementRequest);
            return new ReturnModel(200, updatedStudy, "更新学习管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "更新学习管理记录失败：" + e.getMessage());
        }
    }

    @GetMapping("/get/{id}")
    public ReturnModel getStudyById(@PathVariable String id) {
        try {
            StudyManagementRequest studyManagementRequest = studyManagementService.findById(id);
            return new ReturnModel(200, studyManagementRequest, "获取学习管理记录成功。");
        } catch (Exception e) {
            return new ReturnModel(404, null, "未找到学习管理记录：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    public ReturnModel getStudyList(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String courseName,
            @RequestParam(required = false) Date startDate,
            @RequestParam(required = false) Date endDate) {
        try {
            PagedGridResult<StudyManagement> pagedResult = studyManagementService.getStudyList(page, pageSize, courseName, startDate, endDate);
            return new ReturnModel(200, pagedResult, "获取学习管理记录列表成功。");
        } catch (Exception e) {
            return new ReturnModel(500, null, "获取学习管理记录列表失败：" + e.getMessage());
        }
    }

}
